'use strict';

module.exports = app => {
  const { STRING, INTEGER, JSON, TEXT, BOOLEAN, DATE } = app.Sequelize;

  const AIAnalysisCache = app.model.define('AIAnalysisCache', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    user_id: {
      type: INTEGER,
      allowNull: false,
      comment: '用户ID'
    },
    request_hash: {
      type: STRING(64),
      allowNull: false,
      comment: '请求参数的哈希值'
    },
    clothing_count: {
      type: INTEGER,
      allowNull: false,
      comment: '分析时的衣服数量'
    },
    weather_info: {
      type: JSON,
      allowNull: true,
      comment: '天气信息'
    },
    ai_provider: {
      type: STRING(50),
      allowNull: false,
      comment: 'AI提供商'
    },
    ai_model: {
      type: STRING(100),
      allowNull: true,
      comment: 'AI模型名称'
    },
    ai_analysis: {
      type: TEXT('long'),
      allowNull: false,
      comment: 'AI原始分析结果'
    },
    recommendations: {
      type: JSON,
      allowNull: false,
      comment: '生成的搭配推荐'
    },
    token_usage: {
      type: JSON,
      allowNull: true,
      comment: 'Token使用情况'
    },
    response_time: {
      type: INTEGER,
      allowNull: true,
      comment: 'AI响应时间（毫秒）'
    },
    is_valid: {
      type: BOOLEAN,
      allowNull: false,
      defaultValue: true,
      comment: '缓存是否有效'
    }
  }, {
    tableName: 'ai_analysis_cache',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    indexes: [
      {
        fields: ['user_id']
      },
      {
        fields: ['request_hash']
      },
      {
        unique: true,
        fields: ['user_id', 'request_hash']
      },
      {
        fields: ['created_at']
      }
    ]
  });

  // 关联关系
  AIAnalysisCache.associate = function() {
    // 关联用户
    AIAnalysisCache.belongsTo(app.model.User, {
      foreignKey: 'user_id',
      as: 'user'
    });
  };

  return AIAnalysisCache;
};
